<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>爵士鼓</title>
		<link rel="stylesheet" type="text/css" href="style.css"/>
	</head>

	<body>

		<div class="keys">
			<div data-key="A" class="key">
				<kbd>A</kbd>
				<span class="sound">clap</span>
			</div>
			<div data-key="S" class="key">
				<kbd>S</kbd>
				<span class="sound">hihat</span>
			</div>
			<div data-key="D" class="key">
				<kbd>D</kbd>
				<span class="sound">kick</span>
			</div>
			<div data-key="F" class="key">
				<kbd>F</kbd>
				<span class="sound">openhat</span>
			</div>
			<div data-key="G" class="key">
				<kbd>G</kbd>
				<span class="sound">boom</span>
			</div>
			<div data-key="H" class="key">
				<kbd>H</kbd>
				<span class="sound">ride</span>
			</div>
			<div data-key="J" class="key">
				<kbd>J</kbd>
				<span class="sound">snare</span>
			</div>
			<div data-key="K" class="key">
				<kbd>K</kbd>
				<span class="sound">tom</span>
			</div>
			<div data-key="L" class="key">
				<kbd>L</kbd>
				<span class="sound">tink</span>
			</div>
		</div>

		<audio data-key="A" src="sounds/clap.wav"></audio>
		<audio data-key="S" src="sounds/hihat.wav"></audio>
		<audio data-key="D" src="sounds/kick.wav"></audio>
		<audio data-key="F" src="sounds/openhat.wav"></audio>
		<audio data-key="G" src="sounds/boom.wav"></audio>
		<audio data-key="H" src="sounds/ride.wav"></audio>
		<audio data-key="J" src="sounds/snare.wav"></audio>
		<audio data-key="K" src="sounds/tom.wav"></audio>
		<audio data-key="L" src="sounds/tink.wav"></audio>
	</body>

	<script type="text/javascript">
		function playSound(e) {
			var data = String.fromCharCode(e.keyCode);
//			var reg = /^[A-Za-z0-9]$/;
			var reg = /^\w$/;
			if (!reg.test(data)) {
				return;
			}

			var audio = document.querySelector("audio[data-key="+data+"]");
			var key = document.querySelector("div[data-key="+data+"]");
			if (!audio) {
				return;
			}


			if (!key) {
				return;
			}

			key.classList.add('playing');
			audio.currentTime = 0;
			audio.play();
		}

		window.addEventListener('keydown', playSound);

		function removeTransition(e) {
			if (e.propertyName !== 'transform') {
				return;
			}
//			e.target.classList.remove('playing');
			this.classList.remove('playing');
		}

		var keys = Array.from(document.querySelectorAll('.key'));
		keys.forEach(function (key, index, arr) {
			key.addEventListener('transitionend', removeTransition);
		}, this)


	</script>
</html>
